//
//  DLauncherController.swift
//  Drop
//
//  Created by hushaohua on 2019/2/1.
//  Copyright © 2019 init. All rights reserved.
//

import UIKit
import UserNotifications

class DLauncherController: NSObject, UNUserNotificationCenterDelegate {
    
    func requestNotificationAuthorization() -> Void{
        let notify = UNUserNotificationCenter.current();
        notify.delegate = self;
//        let category = UNNotificationCategory(identifier: "", actions: [], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction);
//        notify.setNotificationCategories([category]);
        weak var weakSelf = self;
        if !DPreferences.defaultInstance.doNotDisturb {
            notify.getNotificationSettings { (settings) in
                weakSelf?.handleNotificationSettings(settings);
            };
        }
    }
    
    func handleNotificationSettings(_ settings:UNNotificationSettings){
        let notify = UNUserNotificationCenter.current();
        switch settings.authorizationStatus {
        case .notDetermined:
            notify.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            };
        default:
            weak var weakSelf = self;
            notify.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
                if !granted {
                    DispatchQueue.main.async {
                        weakSelf?.showNotificationSettingsAlert();
                    }
                }
            };
            break;
        }
    }
    
    func showNotificationSettingsAlert() {
        let alert = UIAlertController.standardAlert("提示", message: "应用的通知已被关闭，为了更好提醒你记录时间，请去系统设置开启通知权限", okAction: {
            let url = URL(string: UIApplicationOpenSettingsURLString);
            UIApplication.shared.open(url!, options: [:], completionHandler: { (completed) in
            });
        }, cancelAction: {
        });
        alert.show();
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        //        DDroppingManager.sharedManager().viewManager.gotoFinish();
        completionHandler(.alert);
    }

    func start() {
        if DDateManager.sharedManager().startedBefore() {
            DDateManager.sharedManager().start();
            self.requestNotificationAuthorization();
        }else{
            HStoreManager.defaultInstance.loadStoreIf();
        }
    }
}
